<?php

namespace App\Http\Controllers\Api;

use App\Models\Advice;
use App\Models\Kefu;
use App\Repositories\Api\AdviceRepository;
use App\Repositories\Api\BannerRepository;
use App\Repositories\Api\KefuRepository;
use App\Repositories\Api\MemberRepository;
use App\Repositories\QuestionRepository;
use App\Repositories\FileRepository;
use App\Repositories\CollegeRepository;
use App\Repositories\WechatRepository;
use App\Repositories\PictureMappingRepository;

use App\Repositories\OccupationRepository;
use App\Repositories\ProfessionRepository;
use App\Http\Services\SendSmsService;

use App\Http\Services\WechatService;
use App\Models\OfficialAccountSubscribe;

use EasyWeChat\MiniProgram\Application;
use EasyWeChat\MiniProgram\Auth\AccessToken;
use Illuminate\Support\Facades\Log;


use App\Models\Member;
use App\Models\MiniShare;
use App\Models\Country;

use Exception;
use Cache;

class HomeController extends MiniAppController
{
    private $memberRep = NULL;

    public function __construct(
        MemberRepository $memberRep
    )
    {
        parent::__construct();
        $this->memberRep = $memberRep;
    }

    public function index()
    {
        return $this->apiResponse->success([
            'project_name' => 'yuexiabixin',
            'version' => env('API_VERSION'),
            'date' => date('Y-m-d'),
            'time' => date('Y-m-d H:i:s'),
        ], 'success', 200, []);
    }

    /**
     * 绑定手机号码
     * @Author   thomashtao               bosslen
     * @DateTime 2022-04-16T14:36:50+0800
     * @return   [type]                   [description]
     */
    public function verify_mobile()
    {
        $params = request()->all();
        if (!$params || !isset($params['code'])) {
            return retFail('参数不完整', 419);
        }
        $res = (new WechatRepository())->getUserPhoneNumber($params['code']);

        if ($res['errcode'] < 0) {
            return retFail("系统繁忙", 400);
        }
        if ($res['errcode'] == 40029) {
            return retFail("不合法的code（code不存在、已过期或者使用过）", 400);
        }
        if ($res['errcode'] == 0) {
            $result = $res['phone_info'];
            $member = Member::where("mobile", "=", $result['purePhoneNumber'])->first();
            if ($member)
                return retFail("该手机号已绑定账号：" . $member['id'] . "昵称:" . $member['username'] . "。", 400);
            $uid = request()->get("wechat_admin_id");
            $c_code = Country::where('code', '=', $result['countryCode'])->value('id');
            $price = get_new_task_price(99);
            $price > 0 && $this->memberRep->change_user_account($uid, null, null, 33, $price, null, 1, nextMonday());
            Member::where("id", "=", $uid)->update(['mobile' => $result['purePhoneNumber'], 'country' => $c_code]);
            return $this->apiResponse->success(['mobile' => $result['purePhoneNumber']], '验证成功！');
        } else {
            return retFail($res['errmsg'], 400);
        }
    }

    public function config()
    {
        $type = request()->get("type");
        $res = (new ConfigRepository())->getConfigDetailByName($type);
        return $this->apiResponse->success($res);
    }

    /**
     * 发送短信
     */
    public function send_sms()
    {
        $param = request()->only('mobile');

        $country_id = request()->get('country_id');
        $country_code = Country::where("id", "=", $country_id)->value("code");
        if (!isMobile($param['mobile']) && $country_code == 86) { //中国检验手机号码是否检测
            return retFail("手机格式错误", 400);
        }

        $sms_cache_key = md5($param['mobile']) . '_sms_code';
        $value = json_decode(Cache::get($sms_cache_key), true);
        if ($value) {
            if (time() - $value['time'] < 120) {
                return retFail("120s内不要频繁发送", 400);
            }
        }

        $code = get_randomstr(6, 'num');
        Cache::put($sms_cache_key, json_encode(['code' => $code, 'time' => time()]), 120);

        // $content = '您的验证码是：' . $code . ' 请勿泄露，如非你本人操作，请忽略。';
        $res = SendSmsService::send($param['mobile'], $code, $country_code);

        return $this->apiResponse->success([], "已发送");
    }

    /**
     * 投诉
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-10T10:33:19+0800
     */
    public function add_complain()
    {
        $params = request()->only("report_uid", "type", "reason");
        $params['uid'] = UID;
        $params['create_time'] = date("Y-m-d H:i:s");

        $picture_ids = request()->post("picture_ids");
        try {
            if (count($picture_ids) == 0)
                return retFail("图片必填", 400);

            $complain_id = (new ComplainRepository())->addCompain($params);
            if ($complain_id) {
                (new PictureMappingRepository())->updateMapping($complain_id, "complain", $picture_ids);
            }

            return $this->apiResponse->success([], "投诉成功，我们会尽快处理");
        } catch (Exception $e) {
            return retFail($e->getMessage(), 400);
        }
    }

    /**
     * @param Request $request
     * 删除文件
     */
    public function delete_file()
    {
        $mid = request()->get('mid', 0);
        if (!$mid) {
            return response([
                'code' => 400,
                'msg' => '参数错误',
                'data' => []
            ], 400);
        }
        $ret = app(FileRepository::class)->removeMapFile($mid);
        return $this->apiResponse->success([], "删除成功");
    }

    /**
     * 上传文件
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-17T18:05:32+0800
     * @return   [type]                   [description]
     */
    public function upload()
    {
        $objectType = (string)request()->object_type;
        $objectId = request()->object_id;
        $subObjectKey = request()->sub_object_key;

        $fileData = request()->file('fileData');
        $res = app(FileRepository::class)->upload($fileData, $objectType, $objectId, $subObjectKey);
        $res['size'] = formatBytes($res['size']);
        $res['full_path'] = getPreviewImage($res['full_path']);

        return response()->json($res);
    }

    /**
     * 支付异步通知
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-28T21:16:44+0800
     * @return   [type]                   [description]
     */
    public function wx_notify()
    {
        (new WechatRepository())->handleWxNotify();
    }

    private function _request_post($url = '', $post_data = [], $header_data = [])
    {

        if (empty($url) || empty($post_data)) {
            return false;
        }
        $ch = curl_init();//初始化curl

        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data, JSON_UNESCAPED_UNICODE));

        if (!empty($header_data)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
        }

        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

    public function test()
    {
        $params = request()->all();
        file_put_contents("/tmp/zhihulog.txt", var_export($params, true) . "\n", 8);

    }

    // 获取广告位
    public function get_banner()
    {
        $name = request()->get("name");
        if (!$name) {
            return $this->apiResponse->success([]);
        }
        $banners = (new BannerRepository())->getBannerByName($name);
        return $this->apiResponse->success([
            'banners' => $banners,
//            'topnavs' => $topnavs,
//            'isHomePageGray' => C('is_home_page_gray')
        ]);
    }


    public function mini_share()
    {
        $pages = request()->get("pages");
        if (empty($pages))
            return retFail("参数错误");

        $pages = get_str_before($pages, '?');// 去掉小程序链接后面的参数
        $res = MiniShare::where(['pages' => $pages, 'status' => 1])->first();
        return $this->apiResponse->success(['shares' => $res]);
    }

    public function mini_share_list()
    {
        $res = MiniShare::where(['status' => 1])->get();
        return $this->apiResponse->success(['share_list' => $res]);
    }

    /**
     * 检查大学相似度
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function check_similar_college()
    {
        $skey = trim(request()->get("skey", ""));

        if (empty($skey))
            return $this->apiResponse->success([]);

        $colleges = (new CollegeRepository())->getList();

        $time = microtime(true);
        $res = check_similar_arr($skey, $colleges);

        return $this->apiResponse->success(['colleges' => $res, 'total' => count($res)]);
    }

    public function profession_list()
    {
        $skey = trim(request()->get("skey", ""));

        if (empty($skey))
            return $this->apiResponse->success([]);

        $res = (new ProfessionRepository())->getList($skey);

        return $this->apiResponse->success(['items' => $res]);
    }

    /**
     * 获取职业
     */
    public function occupation_list()
    {
        $res = (new OccupationRepository())->getLists();
        return $this->apiResponse->success($res);
    }

    /**
     * 获取目前状态
     */
    public function current_status()
    {
        $res = current_status();
        return $this->apiResponse->success($res);
    }

    public function grab_red_packet()
    {
        // 根据所发红包数量，创建redis红包队列；
        // 客户端访问抢红包API ；
        // web服务器先从redis红包队列 中查询剩余数量；
        // redis队列中有剩余，则在mysql中创建抢购成功，去除红包数量，抢红包成功 ；
        // redis队列中没有剩余，则提示已抢完，抢红包失败。
    }

    public function add_feed_back()
    {
        $params = request()->all();
        $created_at = Advice::query()->where(['pid' => 0, 'uid' => UID])->orderby("create_time", "desc")->value('create_time');
        if ($created_at && intval(time() - strtotime($created_at)) < 5) {
            return retFail("不要频繁提交");
        } else {
            if ($params['content']) {
                $data['content'] = trim($params['content']);
                $data['uid'] = UID;

                if (!empty($params['pid'])) {
                    $data['pid'] = $params['pid'];

                    $feedback = (new AdviceRepository())->getOne($data['pid']);
                    $a_data['update_time'] = date("Y-m-d H:i:s");
                    if ($feedback && $feedback['status'] == 1) { //重新开启工单
                        $a_data['status'] = 0;
                    }
                    Advice::where(['id' => $feedback['id']])->update($a_data);
                }

                $data['create_time'] = date("Y-m-d H:i:s");
                $data['update_time'] = date("Y-m-d H:i:s");
                $last_id = Advice::insertGetId($data);

                if ($last_id) {
                    $picture_ids = $params['picture_ids'];

                    if ($picture_ids) {
                        (new PictureMappingRepository())->updateMapping($last_id, "advice", $picture_ids);
                    }

                    //发送模板消息
                    $send_temp_list = explode(',', C("send_temp_list"));
                    if (in_array(UID, $send_temp_list)) {// 发给问题反馈人
                        $advice = Advice::query()->where('id', "=", $params['pid'])->first();
                        $openid = Member::where('id', '=', $advice['uid'])->value('openid');
                        $openid_list[0] = $openid;
                    } else {// 发给管理员
                        $openid_list = Member::whereIn('id', $send_temp_list)->pluck('openid');
                    }

                    foreach ($openid_list as $k => $v) {
                        $v && sendTemplateMsg($v, 17, ['content' => $data['content'],
                            'page' => 'member/advice/reply?id=' . ($data['pid'] ?? $last_id)], 16);
                    }

                    return $this->apiResponse->success([], '感谢反馈');
                } else {
                    return retFail("提交失败", 400);
                }
            } else {
                return retFail("数据异常");
            }
        }
    }

    /**
     *  增加图片回复
     */
    public function add_advice_reply_pic()
    {
        $advice_id = request()->post("advice_id");
        if (empty($advice_id))
            return retFail("数据错误");
        $advice = Advice::query()->where(['id' => $advice_id])->first();

        if (empty($advice))
            return retFail("数据错误");

        $fileData = request()->file('fileData');
        if (empty($fileData))
            return retFail("数据错误");

        $res = app(FileRepository::class)->upload($fileData, "");
        if (empty($res['path']))
            return retFail("回复失败");

//        $res['size'] = formatBytes($res['size']);
//        $res['full_path'] = getPreviewImage($res['full_path']);

        $data['content'] = "";
        $data['uid'] = UID;
        $data['pid'] = $advice_id;
        $data['path'] = $res['path'] ?? "";
        $data['create_time'] = date("Y-m-d H:i:s");
        $last_id = Advice::insertGetId($data);

        //更新工单时间
        $a_data['update_time'] = date("Y-m-d H:i:s");
        if ($advice && $advice['status'] == 1) { //重新开启工单
            $a_data['status'] = 0;
        }
        Advice::where(['id' => $advice['id']])->update($a_data);

        return $this->apiResponse->success([
            'id' => $last_id,
            'add_time_format' => HumanTime(date("Y-m-d H:i:s")),
            'path' => $res['path'] ?? ""
        ], "回复成功");

    }

    public function get_feed_back()
    {
        $id = trim(request()->get("id", ""));
        $advice = (new AdviceRepository())->getOne($id);

        $res['advice'] = $advice;
        return $this->apiResponse->success($res);
    }

    /**
     * 意见反馈-回复
     */
    public function advice_reply()
    {
        $filter['pid'] = request()->get("advice_id");
        $res = (new AdviceRepository())->getReplyList($filter, $this->pageSize, $this->pageNum);
        return $this->apiResponse->success($res);
    }

    /**
     * 问题-相似问题
     */
    public function get_similar_question()
    {
        $skey = trim(request()->get("keyword", ""));
        if (empty($skey))
            return $this->apiResponse->success([]);

        if (mb_strlen($skey) < 2)
            return $this->apiResponse->success([]);

        $skey = Transmeaning::trans($skey);
        if (empty($skey))
            return $this->apiResponse->success([]);

        $questions = (new QuestionRepository())->getList();
        $res = check_similar_arr($skey, $questions, true, 1, 'keyword');
        return $this->apiResponse->success(['items' => $res, 'total' => count($res)]);
    }

    /**
     * @return kefu
     */
    public function kefu()
    {
        $member = $this->memberRep->getOne(UID);
        $kefu = (new KefuRepository())->getOneByCity(get_user_city($member), $member['gender']);

        return retSuc(['kefu' => $kefu]);
    }

}

